<script setup>
import { ref, watch, onMounted } from "vue";
// import { ElMessage } from "element-plus";
// import { pageQueryEmp } from "@/api/emp";
import { queryAllDepts } from "@/api/dept"; //从dept.js中导入queryAll函数
// import { pageQueryEmp,addEmp } from '@/api/emp'; //←增加引入addEmp函数
// import { ElMessage } from "element-plus";
// import { pageQueryEmp,addEmp,getEmpById } from '@/api/emp'; //←增加引入getById函数
// import { pageQueryEmp,addEmp,getEmpById, updateEmpById } from '@/api/emp'; //←增加引入updateById函数
import { pageQueryEmp, addEmp, getEmpById, updateEmpById,deleteEmpByIds } from '@/api/emp'; //←增加引入deleteByIds函数
import { ElMessage, ElMessageBox } from "element-plus"; //增加引入ElMessageBox

const token = ref("");
// 钩子函数：页面一打开就立即搜索员工列表
onMounted(async () => {
  search();
  const result = await queryAllDepts();
  if (result.code == 1) {
    depts.value = result.data;
  }
  //↓↓↓↓↓从localStorage中获取当前用户的令牌，设置给token数据↓↓↓↓↓
  const loginInfo = localStorage.getItem("loginInfo");
  if (loginInfo) {
    token.value = JSON.parse(loginInfo).token;
  }
})
//保存员工
const saveEmp = async ()=>{
  let result;
  if(emp.value.id){ //如果有id，则执行修改操作
    result = await updateEmpById(emp.value);
  }else{ //如果没有id，则执行新增操作
    result = await addEmp(emp.value);
  }
  if (result.code==1) {
    ElMessage.success("保存员工成功");
    dialogFormVisible.value = false;
    search();
  }
}
// //新增员工
// const saveEmp = async ()=>{
//   const result = await addEmp(emp.value);
//   if (result.code==1) {
//     ElMessage.success("保存员工成功");
//     dialogFormVisible.value = false;
//     search();
//   }
// }
//文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response,uploadFile) => {
  emp.value.image = response.data
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}

const genders = ref([ //所有性别选项，直接定义好数据
  {value:1, name:"男"},
  {value:2, name:"女"}
]);
const jobs = ref([ //所有职位选项，直接定义好数据
  {value:1, name:"班主任"},
  {value:2, name:"讲师"},
  {value:3, name:"学工主管"},
  {value:4, name:"教研主管"},
  {value:5, name:"咨询师"}
]);
const depts = ref([]); //所有部门选项，需要页面一加载完成后 立即向后端发请求查询得到所有部门

const dialogFormVisible = ref(false); //dialog窗口是否显示
const dialogTitle = ref("新增员工"); //dialog窗口的标题 

//显示新增窗口
const showAddWin = () => {
  dialogFormVisible.value = true;
  dialogTitle.value = "新增员工";
  emp.value = {
  "image": "",
  "username": "",
  "name": "",
  "gender": "",
  "job": "",
  "entryDate": "",
  "deptId": "",
  "phone": "",
  "salary": "",
  "exprList": []
};
}


//显示修改窗口：查询回显
const handleEdit = async (index, row) => {
  dialogFormVisible.value = true;
  dialogTitle.value = "修改员工";
  //向后端发请求获取员工数据
  const result = await getEmpById(row.id);
  if (result.code==1) {
    emp.value = result.data;
    //处理每个工作经历
    let exprList = emp.value.exprList;
    if (exprList && exprList.length>0) {
      exprList.forEach(expr => {
        expr.exprDate = [expr.begin, expr.end];
      });
    }
  }
}
// //显示修改窗口：查询回显
// const handleEdit = (index, row)=>{
//   //todo 向后端发请求获取员工数据
//   dialogFormVisible.value = true;
//   dialogTitle.value = "修改员工";
// }
const emp = ref({ //dialog里表单所绑定的数据对象。后期要提交到后端，所以必须与API接口文档里的参数一致
  "image": "",
  "username": "",
  "name": "",
  "gender": "",
  "job": "",
  "entryDate": "",
  "deptId": "",
  "phone": "",
  "salary": "",
  "exprList": []
});
// 添加工作经历
const addExpr = () => {
  emp.value.exprList.push({exprDate:[], company:"", job:"", begin:"", end:""});
}
// 删除工作经历
const deleteExpr = (index)=>{
  emp.value.exprList.splice(index, 1); //删除数组中指定索引的数据，删除数量为1条
}

// 监听工作经历中的exprDate变化，监听的是对象，所以需要深度监听
watch(()=>emp.value.exprList, (newV,oldV)=>{
  // 一旦工作经历有变化，就将每个工作经历的exprDate(开始与结束日期数组)中的值，分别赋值给此工作经历的begin与end
  newV.forEach(expr => {
    if(expr.exprDate && expr.exprDate.length >= 2){
      expr.begin = expr.exprDate[0];
      expr.end = expr.exprDate[1];
    }
  });
}, {deep:true});

//定义数据
const searchForm = ref({
  name: "",
  gender: "",
  begin: "",
  end: "",
  daterange: []
});
const tableData = ref([]);
const page = ref(1);
const pageSize = ref(5);
const total = ref(0);

//监听searchForm里的daterange：如果值有变化，就取开始日期赋值给begin，结束日期赋值给end
watch(() => searchForm.value.daterange, (newValue, oldValue) => {
  //如果改变之后的新值非空，并且数组的长度为2，再执行：
  if (newValue && newValue.length == 2) {
    searchForm.value.begin = newValue[0];
    searchForm.value.end = newValue[1];
  }
});

async function search() {
  //todo 暂时将页码和每页数量参数写死了，等后续添加了分页功能之后，要获取实际的页码和分页数量
  const result = await pageQueryEmp(searchForm.value, page.value, pageSize.value);
  if (result.code == 1) {
    //取分页查询结果的列表，设置给表格
    tableData.value = result.data.rows;
    //取分页查询结果的总数量：
    total.value = result.data.total;
  } else {
    ElMessage.error("查询员工失败");
  }
}

//每页数量变化时触发
const handleSizeChange = (val) => {
  //将页码重置为1
  page.value = 1;
  //再向后端发请求
  search();
}
//当前页码变化时触发
const handleCurrentChange = (val) => {
  //重新向后端发请求查询员工列表
  search();
}

function research() {
  // 将搜索条件全部置空
  searchForm.value = {
    name: "",
    gender: "",
    begin: "",
    end: "",
    daterange: []
  };
  // 重新向后端发请求
  search();
}

// //当表格选中行变化时触发的，val是 所有被选中的行数据
// const handleSelectionChange = (val) => {
//   console.log(val);
// }

//删除员工
const handleDelete = (index,row) => {
  ElMessageBox.confirm("确定要删除吗？", "警告", {
    type:"warning",
    cancelButtonText: "取消",
    confirmButtonText: "确定"
  }).then(async ()=>{
    const result = await deleteEmpByIds(row.id);
    if (result.code == 1) {
      ElMessage.success("删除成功");
      search();
    }else{
      ElMessage.error("删除失败");
    }
  });
}

const selectedIds = ref([]); //定义数据，用于存储被选中的id集合
//当表格的复选框变化时触发的函数
const handleSelectionChange = (selection)=>{
  //获取被选中的行记录，将每个行数据的id取出，赋值给selectedIds
  selectedIds.value = selection.map(item => item.id);
}

//批量删除员工
const batchDelete = async () => {
  ElMessageBox.confirm("确定要删除吗？", "警告", {
    type:"warning",
    cancelButtonText: "取消",
    confirmButtonText: "确定"
  }).then(async ()=>{
    const result = await deleteEmpByIds(selectedIds.value);
    if (result.code == 1) {
      ElMessage.success("删除成功");
      search();
    }else{
      ElMessage.error("删除失败");
    }
  });
}
// //当点击“删除”按钮的处理逻辑
// const handleDelete = (index, row) => {
//   console.log(index, row)
// }
</script>

<template>
  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchForm.gender" placeholder="请选择" clearable>
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职日期">
      <el-date-picker v-model="searchForm.daterange" value-format="YYYY-MM-DD" type="daterange" range-separator="到"
        start-placeholder="开始日期" end-placeholder="结束日期" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="research">清空</el-button>
    </el-form-item>
  </el-form>
<!-- 按钮 -->
<el-button type="primary" @click="showAddWin">+ 新增员工</el-button>
<el-button type="primary" @click="batchDelete">- 批量删除</el-button>

<!-- 新增/修改dialog -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
    <!-- 员工表单 -->
    <el-form label-width="80px" :model="emp">
      <!-- 第1行：用户名和姓名 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名">
            <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-input v-model="emp.username" placeholder="请输入员工用户名，2-20个字" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名">
              <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-input v-model="emp.name" placeholder="请输入员工姓名，2-10个字" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第2行：性别和手机号 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" >
              <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-select v-model="emp.gender" placeholder="请选择性别" style="width:100%">
              <el-option v-for="g in genders" :label="g.name" :value="g.value" :key="g.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号">
              <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-input v-model="emp.phone" placeholder="请输入员工手机号" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第3行：职位与薪资 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
              <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-select v-model="emp.job" placeholder="请选择职位" style="width:100%">
              <el-option v-for="j in jobs" :label="j.name" :value="j.value" :key="j.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
              <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-input v-model="emp.salary" placeholder="请输入员工薪资" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第4行：所属部门与入职日期 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
              <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-select v-model="emp.deptId" placeholder="请选择部门" style="width:100%">
              <el-option v-for="d in depts" :label="d.name" :value="d.id" :key="d.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
              <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-date-picker v-model="emp.entryDate" value-format="YYYY-MM-DD" type="date" placeholder="选择入职日期"  style="width:100%"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第5行：头像 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
              <!-- ↓↓↓↓使用v-model绑定数据↓↓↓↓ -->
            <el-upload v-model="emp.image" class="avatar-uploader" action="/api/upload" :show-file-list="false"
              :headers="{'token':token}" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <!-- ↓↓↓↓如果数据emp中的image非空，就显示img标签，src是emp.image↓↓↓↓ -->
              <img v-if="emp.image" :src="emp.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第6行：添加工作经历按钮 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作经历">
              <!-- ↓↓↓↓点击时添加工作经历↓↓↓↓ -->
            <el-button type="success" @click="addExpr">添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第7行：工作经历 -->
        <!-- ↓↓↓↓使用v-for循环emp里的工作经历列表↓↓↓↓ -->
      <el-row :gutter="20" v-for="(expr,index) in emp.exprList" :key="index">
        <el-col :span="9">
          <el-form-item label="时间" label-width="70px">
              <!-- ↓↓↓↓使用v-model将工作的开始与结束日期，绑定给此empr的exprDate↓↓↓↓ -->
            <el-date-picker value-format="YYYY-MM-DD" type="daterange" v-model="expr.exprDate"
              range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公司" label-width="50px">
              <!-- ↓↓↓↓使用v-model将工作公司名称，绑定给此empr的company↓↓↓↓ -->
            <el-input placeholder="请输入公司名称" autocomplete="off" v-model="expr.company"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位" label-width="50px">
              <!-- ↓↓↓↓使用v-model将工作的职位，绑定给此empr的job↓↓↓↓ -->
            <el-input placeholder="请输入职位" autocomplete="off" v-model="expr.job"/>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="" label-width="0">
              <!-- ↓↓↓↓单击时 从emp的工作经历列表中删除此工作经历↓↓↓↓ -->
            <el-button type="danger" @click="deleteExpr(index)">删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEmp">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
    @selection-change="handleSelectionChange">
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column label="姓名" prop="name" width="120"></el-table-column>
    <el-table-column label="性别" prop="gender">
      <template #default="scope">{{ scope.row.gender == 1 ? "男" : "女" }}</template>
    </el-table-column>
    <el-table-column label="头像" prop="image">
      <template #default="scope">
        <img :src="scope.row.image" style="height:50px;">
      </template>
    </el-table-column>
    <el-table-column label="所属部门" prop="deptName"></el-table-column>
    <el-table-column label="职位" prop="job">
      <template #default="scope">
        <!-- 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师 -->
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else>咨询师</span>
      </template>
    </el-table-column>
    <el-table-column label="入职日期" prop="entryDate"></el-table-column>
    <el-table-column label="最后操作时间" prop="updateTime" width="200"></el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<style scoped>
.avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>